package tomsung.cloud.agdc.image;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 图片引擎
 * 
 * @author Junqing Mi
 *
 */
public class ImageEngine {

	private static final Logger logger = LoggerFactory.getLogger(ImageEngine.class);

	private static String BASE_URL;

	private static String BASE_DIR;

	private static String GREEN_HOSE_BASE_URL;

	private static String GREEN_HOSE_BASE_DIR;

	private static int GREEN_HOSE_PAGE_COUNT;

	static {
		Properties prop = new Properties();
		InputStream in = ImageEngine.class.getResourceAsStream("/images/engine.properties");
		try {
			prop.load(in);
			BASE_URL = prop.getProperty("ImagePath");
			BASE_DIR = prop.getProperty("ImageDocBase");
			GREEN_HOSE_BASE_URL = prop.getProperty("GreenHoseImagePath");
			GREEN_HOSE_BASE_DIR = prop.getProperty("GreenHoseImageDocBase");
			GREEN_HOSE_PAGE_COUNT = Integer.parseInt(prop.getProperty("GreenHoseImagePageCount"));
		} catch (Exception e) {
			logger.error("load image base error", e);
		}
	}

	/**
	 * 
	 * @param base64
	 * @return
	 */
	public static String createImage(String base64) {
		int p = base64.indexOf(';');
		String extension = "." + base64.substring(0, p);
		String file = getUUID() + extension;
		String body = base64.substring(p + 1);
		boolean ok = ImageBase64Util.instanceImage(body, BASE_DIR + file);
		return ok ? BASE_URL + file : null;
	}

	/**
	 * 生成唯一文件名，单机可以保证，后续如果需要再进行重写
	 * 
	 * @return
	 */
	private static String getUUID() {
		return UUID.randomUUID().toString();
	}

	/**
	 * 根据大棚ID和时间获取时间之前的图片
	 * 
	 * @param greenhouseId
	 * @param date
	 * @return
	 */
	public static List<String> getGreenHouseImages(int greenhouseId, String date) {
		File dir = new File(GREEN_HOSE_BASE_DIR + greenhouseId);
		File[] files = dir.listFiles();
		List<File> befores = new ArrayList<File>();
		// 根据日期筛选出指定日期之前的数据
		if (files != null && files.length > 0)
		{
			for (File file : files) {
				String fname = file.getName();
				String fdate = fname.substring(0, 14);
				if (date.compareTo(fdate) > 0) {
					befores.add(file);
				}
			}
		}

		// 从大到小排序
		Collections.sort(befores, new Comparator<File>() {

			@Override
			public int compare(File o1, File o2) {
				String fdate1 = o1.getName().substring(0, 14);
				String fdate2 = o2.getName().substring(0, 14);
				return fdate2.compareTo(fdate1);
			}
		});

		// 取前GREEN_HOSE_PAGE_COUNT数据
		int count = befores.size() < GREEN_HOSE_PAGE_COUNT ? befores.size() : GREEN_HOSE_PAGE_COUNT;
		ArrayList<String> result = new ArrayList<String>(count);
		for (int i = 0; i < count; i++) {
			result.add(GREEN_HOSE_BASE_URL + greenhouseId + "/" + befores.get(i).getName());
		}

		return result;
	}

}
